from django.shortcuts import render
from django.views import View
from django import http
from django.contrib.auth import login

import re

from .models import User


class RegisterView(View):
    """注册"""
    def get(self, request):
        """展示注册界面"""
        return render(request, 'register.html')

    def post(self, request):
        """注册逻辑"""
        # 1.接收请求体表单数据
        query_dict = request.POST
        username = query_dict.get('username')
        password = query_dict.get('password')
        password2 = query_dict.get('password2')
        mobile = query_dict.get('mobile')
        sms_code = query_dict.get('sms_code')
        allow = query_dict.get('allow')  # 如果选项框没有指定value值时，勾选了的值为'on' 不勾选为None

        # 2.校验 None False '' [] {}
        if all([username, password, password2, mobile, sms_code, allow]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match('^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')

        if not re.match('^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')

        if password2 != password:
            return http.HttpResponseForbidden('两次输入的密码不一致')

        if not re.match('^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')

        # TODO: 校验短信验证码逻辑后期补充

        # 3.处理业务逻辑：新增
        # user = User.objects.create(username=username, password=password, mobile=mobile)
        # user.set_password(password)
        # user.save()

        user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # 记录用户登录状态：状态保持
        # 将当前用户的id值存储到session中会生成一个session_id 下次请求时都会把所有cookie带过来
        # 如果cookie中有session_id 并能取到session记录及里面的id 就说明是登录用户
        login(request, user)
        
        # 4.响应
        return http.HttpResponse('用户注册成功即代表登录成功，登录成功跳转到首页')
